package com.base.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.base.domain.SysDict;
import com.base.enums.DeletedEnum;
import com.base.mapper.SysDictMapper;
import com.base.service.SysDictService;
import com.base.utils.BeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author gxd
 * @since 2025/6/6
 */
@Slf4j
@Service
public class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDict> implements SysDictService {

    /**
     * 分页列表-字典列表
     * @param dict 字典查询条件
     * @return 字典列表
     */
    @Override
    public List<SysDict> pageList(SysDict dict) {
        List<SysDict> list = this.list(
                Wrappers.lambdaQuery(SysDict.class)
                        .eq(SysDict::getDeleted, DeletedEnum.NO.getCode())
                        .like(StrUtil.isNotBlank(dict.getDictName()), SysDict::getDictName, dict.getDictName())
                        .like(StrUtil.isNotBlank(dict.getDictCode()), SysDict::getDictCode, dict.getDictCode())
                        .eq(ObjUtil.isNotNull(dict.getStatus()), SysDict::getStatus, dict.getStatus())
                        .orderByAsc(SysDict::getSort)
        );
        return list;
    }

    /**
     * 添加或修改-字典信息
     * @param dict 字典实体
     * @return 字典信息
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public SysDict addOrEdit(SysDict dict) {
        Assert.notNull(dict, "字典信息不能为空");
        if (ObjUtil.isNotNull(dict.getId())) {
            SysDict dictInfo = Assert.notNull(this.getById(dict.getId()), "要修改的字典记录不存在");
            BeanUtils.copyNotEmptyProperties(dict, dictInfo);
            this.updateById(dictInfo);
            return dictInfo;
        }

        dict.setDeleted(DeletedEnum.NO.getCode());
        this.save(dict);
        return dict;
    }
}
